//
//  HRTouchManager.m
//  Pods
//
//  Created by duanhuifen on 2017/7/24.
//
//

#import "HRTouchManager.h"
#import <objc/runtime.h>


@interface HRTouchManager ()<
    UINavigationControllerDelegate,
    UIImagePickerControllerDelegate
    >

@property (nonatomic,strong) NSArray *textArr;

@property (nonatomic,strong) NSArray *iconArr;

@property (nonatomic,strong) NSArray *systemIconArr;

@property (nonatomic,assign) NSInteger itemCount;

@property (nonatomic,assign) NSInteger index;

@property (nonatomic,copy) NSString *title;



//@property (nonatomic,strong) NSMutableArray *itemArr;


@end

@implementation HRTouchManager

//+ (instancetype)sharedManager
//{
//    //Singleton instance
//    static HRTouchManager *manager;
//    
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        
//        manager = [[self alloc] init];
//    });
//    
//    return manager;
//}
//
#pragma mark ==================宏定义和常量==================

#define SYSTEM_VERSION  [[[UIDevice currentDevice] systemVersion] floatValue]

#pragma mark ==================函数==================

//访问URL
static inline BOOL OPEN_URL(NSString *urlStr) {
    if (SYSTEM_VERSION >= 10) {
        urlStr = [NSString stringWithFormat:@"App-%@",urlStr];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:nil];
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlStr]]) {
            return YES;
        } else {
            NSLog(@"无法访问-%@", urlStr);
            return NO;
        }
    } else {
        if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlStr]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
            return YES;
        } else {
            NSLog(@"无法访问-%@", urlStr);
            return NO;
        }
    }
}

#pragma mark ==================初始化==================


- (instancetype)initWithDataSource:(id<HRTouchManagerDataSource>)dataSource andDelegate:(id<HRTouchManagerDelegate>)delegate{
    if (self == [super init]) {
        
        _dataSource = dataSource;
        _delegate = delegate;
        
//没有用 --------start------------
        _itemCount = 1;
        
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(hr_numberOfItemsInTouch:)]) {
            _itemCount = [self.dataSource hr_numberOfItemsInTouch:self];
        }
//没有用 --------end------------
        
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(hr_itemTitlesForInTouch:)]) {
            self.textArr = [self.dataSource hr_itemTitlesForInTouch:self];
        }
        
        [self creatShortCutsWithTitleArr:self.textArr andIconArr:nil];
        
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(hr_itemIconsForCustomInTouch:)]) {
            self.iconArr = [self.dataSource hr_itemIconsForCustomInTouch:self];
            [self updataShortCutsWithIconArr:self.iconArr isSystemIcon:NO];
        }
        
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(hr_itemIconsForSystemType:InTouch:)]) {
           self.systemIconArr = [self.dataSource hr_itemIconsForSystemType:UIApplicationShortcutIconTypeAdd InTouch:self];
           [self updataShortCutsWithIconArr:self.systemIconArr isSystemIcon:YES];
        }
        
    }
    return self;
}

- (instancetype)init{
    if (self == [super init]) {
        
    }
    return self;
}

//创建3dTouch
- (void)creatShortCutsWithTitleArr:(NSArray *)titleArr andIconArr:(NSMutableArray *)iconArr{
    NSMutableArray *shortcutItems = [[NSMutableArray alloc]init];

    if (titleArr.count) {
        for (int i = 0; i < titleArr.count; i++) {
            NSString * titleStr = [NSString stringWithFormat:@"dev://%@",titleArr[i]];
            NSDictionary *info = @{@"scheme":titleStr};
            NSString * typeStr = [NSString stringWithFormat:@"com.risenb.%@",titleArr[i]];

            UIMutableApplicationShortcutItem *item = [[UIMutableApplicationShortcutItem alloc] initWithType:typeStr localizedTitle:titleArr[i] localizedSubtitle:@"" icon:nil userInfo:info];
//            UIMutableApplicationShortcutItem * item = [[UIMutableApplicationShortcutItem alloc] initWithType:typeStr localizedTitle:titleArr[i]];
            [shortcutItems addObject:item];
        }
    }
//    NSArray * newItems = [[shortcutItems reverseObjectEnumerator] allObjects] ;
    [[UIApplication sharedApplication] setShortcutItems:shortcutItems];
}

//点击的每个touch 的方法
- (void)clickWithShortcutItem:(UIApplicationShortcutItem *)shortcutItem{
    __weak typeof(self) weakSelf = self;
    
    [self getIndexWithShortCutItem:shortcutItem];
    
    if (weakSelf.delegate ) {
        [weakSelf.delegate manager:self hr_didSelectItemRowAtIndex:self.index];
    }
}

//获取当前点击的index
- (void)getIndexWithShortCutItem:(UIApplicationShortcutItem *)shortcutItem{
    [_textArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isEqualToString:shortcutItem.localizedTitle]) {
            self.index = idx;
        }
    }];
}

//更新数组图片
- (void)updataShortCutsWithIconArr:(NSArray *)iconArr isSystemIcon:(BOOL)isSystem{
    NSArray * newIcons = [[iconArr reverseObjectEnumerator] allObjects] ;

    // 将 shortcutItems 数组改为可变数组
    NSMutableArray *newShortcutItems = [[UIApplication sharedApplication].shortcutItems mutableCopy];

    for (int i = 0; i <newIcons.count; i++) {
        // 获取第 0 个 shortcutItem
        UIApplicationShortcutItem *shortcutItem = [[UIApplication sharedApplication].shortcutItems objectAtIndex:i];

        // 将 shortcutItem0 的类型由 UIApplicationShortcutItem 改为可修改类型 UIMutableApplicationShortcutItem
        UIMutableApplicationShortcutItem * newShortcutItem = [shortcutItem mutableCopy];
        //        [newShortcutItem setLocalizedTitle:@"按钮1"];
        if (isSystem) {
            [newShortcutItem setIcon:[UIApplicationShortcutIcon iconWithType:[newIcons[i] intValue]]];
        }else{
            [newShortcutItem setIcon:[UIApplicationShortcutIcon iconWithTemplateImageName:newIcons[i]] ];
        }
        // 替换原 ShortcutItem
        [newShortcutItems replaceObjectAtIndex:i withObject:newShortcutItem];
    }
    [UIApplication sharedApplication].shortcutItems = newShortcutItems;
}

#pragma mark ==================系统方法==================

//打开常用系统设置里的东西
- (void)openSettingItem:(HRSettingItem)item{
    NSString *url = @"";
    switch (item) {
        case HRSettingsHome:
            url = @"Prefs:root=SETTING";
            break;
        case HRSettingsAirPlane:
            url = @"Prefs:root=AIRPLANE_MODE";
            break;
        case HRSettingsWifi:
            url = @"Prefs:root=WIFI";
            break;
        case HRSettingsBluetooth:
            url = @"Prefs:root=Bluetooth";
            break;
        case HRSettingsHotSpot:
            url = @"Prefs:root=INTERNET_TETHERING";
            break;
        case HRSettingsNotification:
            url = @"Prefs:root=NOTIFICATIONS_ID";
            break;
        case HRSettingsGeneral:
            url = @"Prefs:root=General";
            break;
        case HRSettingsGeneralAbout:
            url = @"Prefs:root=General&path=About";
            break;
        case HRSettingsPhone:
            url = @"Prefs:root=Phone";
            break;
        case HRSettingsLocationService:
            url = @"Prefs:root=LOCATION_SERVICES";
            break;
    }
    
    if (!OPEN_URL(url)) {
        NSLog(@"\"%@\"-URL无法访问", url);
    }
}

//打开系统功能
- (void)openSystemFunctionItem:(HRFunctionItem)funcItem{
    UIImagePickerController * imagePickVC = [[UIImagePickerController alloc] init];
    imagePickVC.delegate = self;
    imagePickVC.allowsEditing = YES;
    
    switch (funcItem) {
        case HRFunctionItemCamera:{
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                imagePickVC.sourceType = UIImagePickerControllerSourceTypeCamera;
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePickVC animated:YES completion:nil];
            }else{
                NSLog(@"没有摄像头");
            }
        }
            break;
        case HRFunctionItemPhotoLibrary:{
              imagePickVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
              [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePickVC animated:YES completion:nil];
        }
            break;
            
        default:
            break;
    }
    
}

#pragma mark ==================图片选择的代理==================

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    //判断资源类型
//    if ([mediaType isEqualToString:]){
//        //如果是图片
//        UIImage * image = info[UIImagePickerControllerEditedImage];
//        //压缩图片
//        NSData *fileData = UIImageJPEGRepresentation(image, 1.0);
//        //保存图片至相册
//        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
//    }
}

#pragma mark 图片保存完毕的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{
    if (error) {
        NSLog(@"保存过程中发生错误，错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"保存成功.");
    }
}

#pragma mark ==================懒加载==================

- (NSArray *)textArr
{
    if (!_textArr) {
        _textArr = [NSArray array];
    }
    return _textArr;
}

- (NSArray *)iconArr
{
    if (!_iconArr) {
        _iconArr = [NSArray array];
    }
    return _iconArr;
}

- (NSArray *)systemIconArr
{
    if (!_systemIconArr) {
        _systemIconArr = [NSArray array];
    }
    return _systemIconArr;
}



@end
